package cn.kogee.org.service.impl;

import cn.kogee.basic.service.impl.BaseServiceImpl;
import cn.kogee.basic.util.Md5Utils;
import cn.kogee.basic.util.StrUtils;
import cn.kogee.org.domain.Employee;
import cn.kogee.org.mapper.EmployeeMapper;
import cn.kogee.org.service.IEmployeeService;
import cn.kogee.user.domain.Logininfo;
import cn.kogee.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 业务实现类：部门
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    @Transactional
    public void del(Long id) {
        //查询出Employee表整体信息
        Employee employee = employeeMapper.loadById(id);
        //根据Logininfo_id删除相关信息
        logininfoMapper.remove(employee.getLogininfo_id());
        employeeMapper.delRole(id);
        super.del(id);
    }

    @Override
    @Transactional
    public void add(Employee employee) {
        //设置盐值加密
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
        Logininfo logininfo = new Logininfo();
        //设置为管理员
        logininfo.setType(0);
        //设置管理员状态
        logininfo.setDisable(true);
        //拷贝管理员信息
        BeanUtils.copyProperties(employee,logininfo);
        logininfoMapper.save(logininfo);//保存落库
        employee.setLogininfo_id(logininfo.getId());//给管理员设置logininfoId
        super.add(employee);
        if(employee.getRole_id()!=null){
            employeeMapper.addEmployeeAndRole(employee);
        }
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        //设置盐值加密
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
        super.update(employee);
        //根据之前的id查询出之前的管理员信息
        Employee oldemployee = employeeMapper.loadById(employee.getId());
        //在根据之前管理员信息的ID查询出logininfo信息
        Logininfo logininfo = logininfoMapper.loadById(oldemployee.getLogininfo_id());
        //拷贝现在employee表信息
        BeanUtils.copyProperties(employee,logininfo);
        logininfoMapper.update(logininfo);
        //删除之前的ID信息
        employeeMapper.delRole(employee.getId());
        //在新增相关信息
        if(employee.getRole_id()!=null){
            employeeMapper.addEmployeeAndRole(employee);
        }
    }
}
